package com.sduept.nwld.primaryequipment.rest;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.sduept.bigdata.fault.entity.AnalLinefaultEtl;
import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.manager.FaultForecastIdentifyManager;
import com.sduept.bigdata.fault.manager.FaultRecordPersistManager;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.fault.system.properties.FaultSystemProperties;
import com.sduept.bigdata.ml.domain.LibSvmData;
import com.sduept.bigdata.weather.faultcause.manager.FaultCauseManager;
import com.sduept.core.dao.SuperDAO;
@RestController
@RequestMapping("/predict/")
public class FaultReasonPredictService {
	@Autowired
	private SuperDAO dao;
	@Autowired
	private FaultRecordPersistManager frm;
	@Autowired
	private FaultRecordQueryManager fm; 
	@Autowired
	private FaultCauseManager fcm ;
	@Autowired
	private FaultForecastIdentifyManager fim ;
	@Autowired
	private  FaultSystemProperties pros ;
	
	@Resource
	private DataSource serverDatasource;
	

	@GetMapping("/getFaultReasonPredict/{faultId}")
	public String findAllPages(@PathVariable("faultId")String faultId){
		FaultRecord fr = fm.findById(faultId);
		JSONObject obj = new JSONObject();
		List<Object> countList = new ArrayList<Object>();
		Map<String, Double> map = new HashMap<>();
		fr = setFaultRecordLonAndLat(fr);
		AnalLinefaultEtl alf = fim.findAnalLinefaultEtlByFaultRecordId(faultId);
		if(alf==null) {
			alf =  fcm.faultIdentify(fr.getId(), fr.getEquipment_id(), fr.getFaultTime(),
					fr.getLon() == null ? 0 : fr.getLon().doubleValue(),
					fr.getLat() == null ? 0 : fr.getLat().doubleValue(), 1);
		}
		if(alf!=null) {
			LibSvmData data = fcm._getLibSvmDate(alf);
			map =fim.getPredictAccuracyMap(data,pros.getFaultReasonIdentifyPath());//如果模型数据不准确的话，有可能出现主页面预测雷击，该页面预测是其他原因的情况
		}
		for(Entry<String, Double> entry:map.entrySet()) {
			Map<String, Object> countMap = new HashMap<String, Object>();
			countMap.put("name", entry.getKey() );
			countMap.put("value",entry.getValue());
			countList.add(countMap);
		}
		return obj.toJSONString(countList);
	}



	/**
	  * 设置经纬度信息
	  * @param fr
	  * @return
	  */
	 private FaultRecord setFaultRecordLonAndLat(FaultRecord fr) {
	    	List<FaultRecord> faults = new ArrayList<>();
			faults.add(fr);
			faults = frm.setupFaultLonAndLat(faults, true);
			fr = faults.get(0);
			return fr;
	    }
	

	@GetMapping("/getVisitorByPage/{selectedPage}")
	public String findVisitorByPage(@PathVariable("selectedPage") String selectedPage) {
		//传过来的参数有双引号，去掉双引号
		String selected = selectedPage.replace("\"", "");
		JSONObject obj = new JSONObject();
		List<Object> countList = new ArrayList<Object>();
		
		PreparedStatement st = null;
		Connection connect = null;
		ResultSet res = null;
		String sql = "select name,sum(visitCount) visitCount from t_org_audit where page = '"+selected+"' and code !='admin' group by code order by visitCount desc";
		try {
			connect = serverDatasource.getConnection();
			st = connect.prepareStatement(sql);
			res = st.executeQuery(sql);
			while(res.next()){
				String name = res.getString("name");
				Integer count = res.getInt("visitCount");
				Map<String, Object> countMap = new HashMap<String, Object>();
				countMap.put("visitor", name);
				countMap.put("value", count);
				countList.add(countMap);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				res.close();
				connect.close();
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return obj.toJSONString(countList);
	}
	

	@GetMapping("/getProjectAuditLoginTime")
	public String getProjectAuditLoginTime(){
		JSONObject obj = new JSONObject();
		List<Object> countList = new ArrayList<Object>();
		
		PreparedStatement st = null;
		Connection connect = null;
		ResultSet res = null;
		String sql = "select name, loginTime from t_logintime where code!='admin' order by loginTime desc";
		//String sql = "select name, loginTime from t_logintime order by loginTime desc";
		try {
			connect = serverDatasource.getConnection();
			st = connect.prepareStatement(sql);
			res = st.executeQuery(sql);
			while(res.next()){
				String name = res.getString("name");
				Integer count = res.getInt("loginTime");
				Map<String, Object> countMap = new HashMap<String, Object>();
				countMap.put("name", name);
				countMap.put("loginTime", count);
				countList.add(countMap);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				res.close();
				connect.close();
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return obj.toJSONString(countList);
	}
}
